<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch, toRaw } from "vue";
import { getDeviceConfigApi, setDeviceConfigApi } from '@/api/configs/deviceConfig';
import { useI18n } from "vue-i18n";
import { DeviceModel } from "@/api/products/device";
import { formatTimestampToDatetime } from "@/utils/appCommon/timeUtil";
import { ElMessageBox, ElMessage } from "element-plus";
import { IsBelongVI, IsBelongVI1 } from "@/utils/appCommon/appCommonOptions/products";
import CopyDevices from './CopyDevices.vue';

const emit = defineEmits(['onsubmit']);

const props = defineProps({
  params: {
    type: Object,
    required: true
  },
  deviceNo: {
    type: String,
    required: true
  },
  deviceOptions: {
    type: Array,
    required: false,
    default: [],
  },
  forceRefresh: {
    type: Number,
    required: false,
    default: 0
  }
});

interface ViMeasureConfItem {
  viMeasureType: number;
  viMeasureFreq: number;
  viMeasureTimes: number;
  viMeasurePoints: number;
  viMeasureSleep: number;
  viFirLow: number;
  viFirHigh: number;
  viFirAmp: number;

  viOffsetX: number;
  viOffsetY: number;
  viOffsetZ: number;
  viFactorX: number;
  viFactorY: number;
  viFactorZ: number;

  viRange: number;
  viWaveEnable: boolean;
  viMeasureState: boolean;
  viSystemTime: number;
  viConfigVersion: number;
  viSaveLoop: number;
  viOffsetTemperature: number;
  scheduleVersion: number;
  viRemoveAccX: boolean;
  viRemoveAccY: boolean;
  viRemoveAccZ: boolean;
  updatetime?: number;
}

const i18n = useI18n();

const current = ref(
  {
    configKey: "viMeasure",
    deviceNo: "",
    productId: 0,
    productKey: "",
    updatedAt: 0,
  }
)
const currentDeviceInfo = ref<DeviceModel>();
// 复制设备配置
const copyDevices = ref<string[]>([]);

const form = ref<ViMeasureConfItem>({
  viMeasureType: 0,
  viMeasureFreq: 1,
  viMeasureTimes: 0,
  viMeasurePoints: 1024,
  viMeasureSleep: 0,
  viFirLow: 0,
  viFirHigh: 2000,
  viFirAmp: 0,

  viOffsetX: 0,
  viOffsetY: 0,
  viOffsetZ: 0,
  viFactorX: 1,
  viFactorY: 1,
  viFactorZ: 1,

  viRange: 0,
  viWaveEnable: false,
  viMeasureState: false,
  viSystemTime: 0,
  viConfigVersion: 0,
  viSaveLoop: 0,
  viOffsetTemperature: 0,
  scheduleVersion: 0,
  viRemoveAccX: false,
  viRemoveAccY: false,
  viRemoveAccZ: false,
});

// 采样频率选项
const freqOptions = [
  { label: '1 KHz', value: 1 },
  { label: '2 KHz', value: 2 },
  { label: '4 KHz', value: 4 }
];

// 采样点数选项
const pointsOptions = [1024, 2048, 4096];

const systemTime = computed(() => {
  if (!current.value.updatedAt || current.value.updatedAt == 0) {
    return "-";
  }
  return formatTimestampToDatetime(current.value.updatedAt)
})

const loading = ref(false);

// 监听属性变化
watch(
  () => props,
  (newVal) => {
    current.value.updatedAt=0
    current.value.deviceNo = newVal.deviceNo;
    current.value.productId = newVal.params.productId;
    current.value.productKey = newVal.params.productKey;
    if(IsBelongVI1(current.value.productKey)){
      form.value.viMeasureType = 0
    }else{
      form.value.viMeasureType = 1
    }

    setTimeout(async () => {
      await loadConfig();
    })
  }, { deep: true, immediate: true }
);

// 获取最大低通滤波值（采样频率的一半）
const maxFirHigh = computed(() => {
  const freqMap: Record<number, number> = {
    1: 500, // 1KHz 采样率对应 500Hz 最大低通
    2: 1000, // 2KHz 采样率对应 1000Hz 最大低通
    4: 2000 // 4KHz 采样率对应 2000Hz 最大低通
  };
  return freqMap[form.value.viMeasureFreq] || 2000;
});

// 加载配置
const loadConfig = async () => {
  try {
    loading.value = true;
    const res = await getDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
    });
    if (res.data?.configValue) {
      form.value = JSON.parse(res.data?.configValue);
      form.value.updatetime =  res.data?.updatedAt
      // 更新当前时间戳
      if (form.value.updatetime) {
        current.value.updatedAt = form.value.updatetime;
      }
    }
    if(IsBelongVI1(current.value.productKey)){
      form.value.viMeasureType = 0
    }else{
      form.value.viMeasureType = 1
    }
  } finally {
    loading.value = false;
  }
};

// 保存配置
const saveConfig = async () => {
  try {
    loading.value = true;
    await setDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
      configValue: form.value,
      copyDevices: copyDevices.value
    });
    ElMessage.success(i18n.t('messages.saveSuccess'));
  } finally {
    loading.value = false;
  }
};

// 验证表单
const validateForm = () => {
  // 验证高通滤波不大于低通滤波
  if (form.value.viFirHigh > form.value.viFirLow) {
    ElMessage.error(i18n.t('device.vimeasure.vi_fir_high') + ' must be less than or equal to ' + i18n.t('device.vimeasure.vi_fir_low'));
    return false;
  }

  // 验证低通滤波不大于采样频率的一半
  if (form.value.viFirLow > maxFirHigh.value/2) {
    ElMessage.error(i18n.t('device.vimeasure.vi_fir_low') + ' must be less than or equal to half of the sampling frequency (' + maxFirHigh.value/2 + 'Hz)');
    return false;
  }

  return true;
};

// 修改保存配置方法，添加二次确认
const handleSaveConfig = async () => {
  try {
    // 先验证表单
    if (!validateForm()) {
      return;
    }

    // 显示确认对话框
    await ElMessageBox.confirm(
      i18n.t('buttons.tips.confirmSaveConfig') + "?",
      "",
      {
        confirmButtonText: i18n.t('buttons.confirm'),
        cancelButtonText: i18n.t('buttons.cancel'),
        type: 'warning'
      }
    );
    // 用户确认后执行保存操作
    await saveConfig();
    // 重新加载配置以更新时间戳
    setTimeout(async ()=>{
      await loadConfig();
    },2000)
  } catch (error) {
    // 用户取消或其他错误，不做任何操作
    console.log('保存已取消');
  }
};

onMounted(() => {
});
</script>

<template>
  <div class="vi-measure-config">
    <el-form :model="form" label-width="150px">
      <el-form-item :label="i18n.t('device.deviceNo')" prop="deviceNo">
        <el-input v-model="current.deviceNo" disabled />
      </el-form-item>

      <el-form-item :label="i18n.t('device.vimeasure.vi_measure_type')" prop="viMeasureType">
        <el-radio-group v-model="form.viMeasureType" disabled>
          <el-radio :label="0">{{ i18n.t('device.vimeasure.vi_single_axis') }}</el-radio>
          <el-radio :label="1">{{ i18n.t('device.vimeasure.vi_triple_axis') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="i18n.t('device.vimeasure.vi_measure_interval')" prop="viMeasureFreq">
        <el-select v-model="form.viMeasureFreq" style="min-width: 200px;">
          <el-option
            v-for="option in freqOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="i18n.t('device.vimeasure.vi_measure_times')" prop="viMeasureTimes">
        <el-input-number v-model.number="form.viMeasureTimes" :min="1" style="min-width: 200px;" />
      </el-form-item>

      <el-form-item :label="i18n.t('device.vimeasure.vi_measure_points')" prop="viMeasurePoints">
        <el-select v-model="form.viMeasurePoints" style="min-width: 200px;">
          <el-option
            v-for="option in pointsOptions"
            :key="option"
            :label="option"
            :value="option"
          />
        </el-select>
      </el-form-item>

<!--      <el-form-item :label="i18n.t('device.vimeasure.vi_measure_sleep')+ '(s)'" prop="viMeasureSleep">-->
<!--        <el-input-number v-model.number="form.ViMeasureSleep" :min="0" style="min-width: 200px;" />-->
<!--      </el-form-item>-->
      <text style="margin-left: 30px;color: red">{{i18n.t('device.vimeasure.aeFirTip')}}</text>
      <el-form-item :label="i18n.t('device.vimeasure.vi_fir_high') + ' (Hz)'" prop="viFirHigh">
        <el-input-number v-model.number="form.viFirHigh"  style="min-width: 200px;" />
      </el-form-item>

      <el-form-item :label="i18n.t('device.vimeasure.vi_fir_low') + ' (Hz)'" prop="viFirLow">
        <el-input-number v-model.number="form.viFirLow"  style="min-width: 200px;" />
      </el-form-item>



<!--      <el-form-item :label="i18n.t('device.vimeasure.vi_fir_amp')" prop="viFirAmp">-->
<!--        <el-input-number v-model.number="form.viFirAmp" :min="0" style="min-width: 200px;" />-->
<!--      </el-form-item>-->

      <!-- Z轴参数（单轴和三轴都显示） -->
<!--      <el-form-item :label="i18n.t('device.vimeasure.vi_offset_z')" prop="viOffsetZ">-->
<!--        <el-input-number v-model.number="form.viOffsetZ" style="min-width: 200px;" />-->
<!--      </el-form-item>-->

<!--      <el-form-item :label="i18n.t('device.vimeasure.vi_factor_z')" prop="viFactorZ">-->
<!--        <el-input-number v-model.number="form.viFactorZ" :min="0" style="min-width: 200px;" />-->
<!--      </el-form-item>-->

      <el-form-item :label="i18n.t('device.vimeasure.viRemoveAcc')+'(Z)'" prop="viRemoveAccZ">
        <el-radio-group v-model="form.viRemoveAccZ">
          <el-radio :label="true">{{ i18n.t('buttons.yes') }}</el-radio>
          <el-radio :label="false">{{ i18n.t('buttons.no') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- X轴和Y轴参数（仅在三轴模式下显示） -->
      <template v-if="form.viMeasureType === 1">
<!--        <el-form-item :label="i18n.t('device.vimeasure.vi_offset_x')" prop="viOffsetX">-->
<!--          <el-input-number v-model.number="form.viOffsetX" style="min-width: 200px;" />-->
<!--        </el-form-item>-->

<!--        <el-form-item :label="i18n.t('device.vimeasure.vi_factor_x')" prop="viFactorX">-->
<!--          <el-input-number v-model.number="form.viFactorX" :min="0" style="min-width: 200px;" />-->
<!--        </el-form-item>-->

        <el-form-item :label="i18n.t('device.vimeasure.viRemoveAcc')+'(X)'" prop="viRemoveAccX">
          <el-radio-group v-model="form.viRemoveAccX">
            <el-radio :label="true">{{ i18n.t('buttons.yes') }}</el-radio>
            <el-radio :label="false">{{ i18n.t('buttons.no') }}</el-radio>
          </el-radio-group>
        </el-form-item>

<!--        <el-form-item :label="i18n.t('device.vimeasure.vi_offset_y')" prop="viOffsetY">-->
<!--          <el-input-number v-model.number="form.ViOffsetY" style="min-width: 200px;" />-->
<!--        </el-form-item>-->

<!--        <el-form-item :label="i18n.t('device.vimeasure.vi_factor_y')" prop="viFactorY">-->
<!--          <el-input-number v-model.number="form.ViFactorY" :min="0" style="min-width: 200px;" />-->
<!--        </el-form-item>-->

        <el-form-item :label="i18n.t('device.vimeasure.viRemoveAcc')+'(Y)'" prop="viRemoveAccY">
          <el-radio-group v-model="form.viRemoveAccY">
            <el-radio :label="true">{{ i18n.t('buttons.yes') }}</el-radio>
            <el-radio :label="false">{{ i18n.t('buttons.no') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </template>

<!--      <el-form-item :label="i18n.t('device.vimeasure.vi_range')" prop="viRange">-->
<!--        <el-input-number v-model.number="form.viRange" :min="0" style="min-width: 200px;" />-->
<!--      </el-form-item>-->

      <el-form-item :label="i18n.t('device.vimeasure.vi_wave_enable')" prop="viWaveEnable">
        <el-radio-group v-model="form.viWaveEnable">
          <el-radio :label="true">{{ i18n.t('buttons.yes') }}</el-radio>
          <el-radio :label="false">{{ i18n.t('buttons.no') }}</el-radio>
        </el-radio-group>
      </el-form-item>

<!--      <el-form-item :label="i18n.t('device.vimeasure.vi_measure_state')" prop="viMeasureState">-->
<!--        <el-radio-group v-model="form.viMeasureState">-->
<!--          <el-radio :label="true">{{ i18n.t('buttons.yes') }}</el-radio>-->
<!--          <el-radio :label="false">{{ i18n.t('buttons.no') }}</el-radio>-->
<!--        </el-radio-group>-->
<!--      </el-form-item>-->

<!--      <el-form-item :label="'Vi Save Loop'" prop="viSaveLoop">-->
<!--        <el-input-number v-model.number="form.viSaveLoop" :min="0" style="min-width: 200px;" />-->
<!--      </el-form-item>-->

<!--      <el-form-item :label="'Vi Offset Temperature'" prop="viOffsetTemperature">-->
<!--        <el-input-number v-model.number="form.viOffsetTemperature" style="min-width: 200px;" />-->
<!--      </el-form-item>-->

      <!-- 复制设备配置 -->
      <el-form-item :label="i18n.t('device.copyDevices.title')">
        <CopyDevices
          :device-no="current.deviceNo"
          v-model="copyDevices"
        />
      </el-form-item>

      <el-form-item :label="i18n.t('device.aeparam.SYSTEM_TIME')">
        <el-input v-model="systemTime" type="text" disabled></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleSaveConfig" style="min-width: 150px;">
          {{ i18n.t('buttons.submit') }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.vi-measure-config {
  padding: 20px;
  overflow-x: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

@media (max-width: 768px) {
  .vi-measure-config {
    padding: 10px;
  }

  .el-form-item__label {
    width: 120px !important;
  }

  .el-form--label-top .el-form-item__label {
    text-align: left;
    padding-bottom: 10px;
  }
}
</style>
